package com.zzxx.photograph.web.servlet;

import com.zzxx.photograph.domain.*;
import com.zzxx.photograph.service.ImgService;
import com.zzxx.photograph.service.impl.ImgServiceImpl;
import com.zzxx.photograph.util.DownLoadUtils;
import com.zzxx.photograph.web.BaseServlet;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/photo/*")
public class ImgServlet extends BaseServlet {
    private ImgService imgService = new ImgServiceImpl();

    // /photo/isFavorite
    public void isFavorite(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String _iid = req.getParameter("iid");
        int iid = Integer.parseInt(_iid);
        ResultInfo info = new ResultInfo();
        // 判断用户是否登录
        Object obj = req.getSession().getAttribute("user");
        if (obj == null) { // 未登录
            info.setFlag(false);
        } else { // 已登录
            User user = (User) obj;
            boolean isFavorite = imgService.imgIsFavorite(iid, user.getUid());
            info.setFlag(isFavorite);
        }
        // 结果返回
        writeValue(resp, info);
    }

    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // pageSize 默认值
        int pageSize = 16;
        String _pageSize = req.getParameter("pageSize");
        if (_pageSize != null && _pageSize.length() > 0) {
            pageSize = Integer.parseInt(_pageSize);
        }
        // currentPage 默认值
        int currentPage = 1;
        String _currentPage = req.getParameter("currentPage");
        if (_currentPage != null && _currentPage.length() > 0) {
            currentPage = Integer.parseInt(_currentPage);
        }
        PageBean<Img> pb = imgService.findAll(currentPage, pageSize);
        writeValue(resp, pb);
    }

    public void favorite(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String _iid = req.getParameter("iid");
        int iid = Integer.parseInt(_iid);
        User user = (User) req.getSession().getAttribute("user");
        // 判断用户是否登录
        if (user == null) { // 未登录
            return;
        } else { // 已登录
            imgService.favorite(iid, user.getUid());
        }
        // 结果返回
        writeValue(resp, true);
    }

    // /route/cancelFavorite
    public void cancelFavorite(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String _iid = req.getParameter("iid");
        int iid = Integer.parseInt(_iid);
        User user = (User) req.getSession().getAttribute("user");
        // 判断用户是否登录
        if (user == null) { // 未登录
            return;
        } else { // 已登录
            imgService.cancelFavorite(iid, user.getUid());
        }
        // 结果返回
        writeValue(resp, true);
    }

    public void myFavorite(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        User user = (User) req.getSession().getAttribute("user");
        // pageSize 默认值
        int pageSize = 8;
        String _pageSize = req.getParameter("pageSize");
        if (_pageSize != null && _pageSize.length() > 0) {
            pageSize = Integer.parseInt(_pageSize);
        }
        // currentPage 默认值
        int currentPage = 1;
        String _currentPage = req.getParameter("currentPage");
        if (_currentPage != null && _currentPage.length() > 0) {
            currentPage = Integer.parseInt(_currentPage);
        }
        PageBean<Img> pb = imgService.findImgsByUid(user.getUid(), pageSize, currentPage);
        // 结果返回
        writeValue(resp, pb);
    }

    public void favoriteCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String _iid = req.getParameter("iid");
        int iid = Integer.parseInt(_iid);
        int cout = imgService.findfavoriteCount(iid);
        writeValue(resp, cout);
    }

    public void imgDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String _iid = req.getParameter("iid");
        int iid = Integer.parseInt(_iid);
        Img img = imgService.findImgByIid(iid);
        writeValue(resp, img);
    }

    public void downloadfile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 文件下载： 文件从服务器端 复制到 客户端
        // 1.获得要下载文件的名字
        String filename = req.getParameter("filename");
        // 2.获得文件的绝对路径
//        String _iid = req.getParameter("iid");
//        int iid = Integer.parseInt(_iid);
//        String src = imgService.findSrcByIid(iid);
        filename = filename.substring(6);
        String path = this.getServletContext().getRealPath("image/" + filename);
//        System.out.println(src);
//        filename = src.substring(6);
//        System.out.println(filename);
//        String path = this.getServletContext().getRealPath("image/11.jpg");
        // 3.复制文件 - 创建读文件的输入流
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
        // 问题1解决：设置响应的内容类型 MimeType - web.xml
        resp.setContentType(this.getServletContext().getMimeType(filename));
        // 问题3[下载后的文件名乱码]解决
        String agent = req.getHeader("user-agent");
        filename = DownLoadUtils.getFileName(agent, filename);
        // 问题2解决：告诉浏览器，是以附件形式打开文件（下载）
        resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
        // 4.复制文件 - 获得响应对应的输出流
        ServletOutputStream os = resp.getOutputStream();
        // 5.文件复制 - 过程
        byte[] bytes = new byte[1024];
        int len = -1;
        while ((len = bis.read(bytes)) != -1) {
            os.write(bytes, 0, len);
        }
        bis.close();
    }

    public void findByFavorite(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // pageSize 默认值
        int pageSize = 4;
        String _pageSize = req.getParameter("pageSize");
        if (_pageSize != null && _pageSize.length() > 0) {
            pageSize = Integer.parseInt(_pageSize);
        }
        // currentPage 默认值
        int currentPage = 1;
        String _currentPage = req.getParameter("currentPage");
        if (_currentPage != null && _currentPage.length() > 0) {
            currentPage = Integer.parseInt(_currentPage);
        }
        PageBean<Img> pb = imgService.findByFavorite(currentPage, pageSize);
        writeValue(resp, pb);
    }

    /*public void insertImg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        try {
            // 接受上传文件
            // 1.创建磁盘文件项工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 2.创建文件上传的核心类
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 3.解析request-获得文件项集合
            List<FileItem> list = upload.parseRequest(req);
            // 4.遍历文件项集合
            for (FileItem item : list) {
                // 判断普通表单项/文件上传项
                boolean formField = item.isFormField();// 是否是一个普通表单项
                // 获得上传文件的名称
                String iname = req.getParameter("iname");
                // 将in中的数据拷贝到服务器上
                String path = this.getServletContext().getRealPath("image");
                String src=(path + "/" + iname);
                if (formField) {
                    // 普通表单项

                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();
                    System.out.println(fieldName + "---" + fieldValue);
                } else {
                    // 文件上传项

                    // 获得上传文件的内容
                    InputStream in = item.getInputStream();
                    // 将in中的数据拷贝到服务器上
                    OutputStream out = new FileOutputStream(src);
                    int len = 0;
                    byte[] buffer = new byte[1024];
                    while ((len = in.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }
                    in.close();
                    out.close();

                }
                Img img=new Img();
                //封装img对象
                Integer id=imgService.getMaxId();
                //封装id
                img.setIid(id+1);
                //封装路径
                img.setIsrc(src);
                //封装图片名
                img.setIname(iname);
                //封装标签
                img.setItag(req.getParameter("tag"));
                String cname = req.getParameter("cname");
                System.out.println(cname);
                Integer cid = imgService.findCid(cname);
                //封装类型
                img.setCid(cid);
                User user = (User) req.getSession().getAttribute("user");
                //封装作者id
                img.setAid(user.getUid());
                Date date = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                img.setIdate(simpleDateFormat.format(date));
                img.setIsize("1920×1280");
                //封装作者对象
                Author author=new Author();
                author.setAid(user.getUid());
                author.setTelephone(user.getTelephone());
                author.setAname(user.getName());
                img.setAuthor(author);
                //-----------------------
                imgService.addImg(img);
                ResultInfo info =new ResultInfo();
                info.setFlag(true);
                writeValue(resp,info);
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }*/
    public void insertImg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uid = null;
        String name = null;
        String itag = null;
        String category = null;
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");
        Img img = new Img();
        User user = (User) req.getSession().getAttribute("user");
        try {
            // 接受上传文件
            // 1.创建磁盘文件项工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 2.创建文件上传的核心类
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 3.解析request-获得文件项集合
            List<FileItem> list = upload.parseRequest(req);
            // 4.遍历文件项集合
            for (FileItem item : list) {
                // 判断普通表单项/文件上传项
                boolean formField = item.isFormField();// 是否是一个普通表单项
                if (formField) {
                    // 普通表单项
                    String fieldName = item.getFieldName();
                    String fieldValue = new String(item.getString().getBytes("iso-8859-1"), "utf-8");
                    if (fieldName.equals("uid")) {
                        Integer id = imgService.getMaxId();
                        //封装id
                        img.setIid(id + 1);
                        //封装作者id
                        img.setAid(user.getUid());
                        Date date = new Date();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        //封装时间
                        img.setIdate(simpleDateFormat.format(date));
                        //封装图片大小
                        img.setIsize("1920×1280");
                        //封装作者对象
                        Author author = new Author();
                        author.setAid(user.getUid());
                        author.setTelephone(user.getTelephone());
                        author.setAname(user.getName());
                        img.setAuthor(author);
                        //封装iclick
                        img.setIclick(0);
                    } else if (fieldName.equals("file")) {
                        //封装路径
                        img.setIsrc("image/" + fieldValue);
                    } else if (fieldName.equals("iname")) {
                        //封装图片名
                        img.setIname(fieldValue);
                    } else if (fieldName.equals("itag")) {
                        //封装标签
                        img.setItag(fieldValue);
                    } else if (fieldName.equals("category")) {
                        //封装类型
                        Integer cid = imgService.findCid(fieldValue);
                        img.setCid(cid);
                    }
                    System.out.println(fieldName + "---" + fieldValue);
                    if (fieldName.equals("uid")) {
                        uid = fieldValue;
                    } else if (fieldName.equals("name")) {
                        name = fieldValue;
                    } else if (fieldName.equals("itag")) {
                        itag = fieldValue;
                    } else if (fieldName.equals("category")) {
                        category = fieldValue;
                    }
                } else {
                    // 文件上传项
                    // 获得上传文件的名称
                    String fileName = item.getName();
                    // 获得上传文件的内容
                    InputStream in = item.getInputStream();
                    // 将in中的数据拷贝到服务器上
                    String path = this.getServletContext().getRealPath("/image");
                    System.out.println("path:" + path);
                    OutputStream out = new FileOutputStream(path + "/" + fileName);
                    System.out.println("fileName:" + fileName);

                    int len = 0;
                    byte[] buffer = new byte[1024];
                    while ((len = in.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }
                    in.close();
                    out.close();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        imgService.addImg(img);
        ResultInfo info = new ResultInfo();
        info.setFlag(true);
        info.setData("上传成功");
        writeValue(resp, info);
    }

    public void findByAid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        // pageSize 默认值
        int pageSize = 4;
        String _pageSize = req.getParameter("pageSize");
        if (_pageSize != null && _pageSize.length() > 0) {
            pageSize = Integer.parseInt(_pageSize);
        }
        // currentPage 默认值
        int currentPage = 1;
        String _currentPage = req.getParameter("currentPage");
        if (_currentPage != null && _currentPage.length() > 0) {
            currentPage = Integer.parseInt(_currentPage);
        }
        PageBean<Img> pb = imgService.findImgByAid(user.getUid(), currentPage, pageSize);
        writeValue(resp, pb);
    }

    public void findByIid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String iid = req.getParameter("iid");
        Img img = imgService.findImgByIid(Integer.parseInt(iid));
        writeValue(resp, img);
    }

    public void updateImg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Img img = new Img();
        String _iid = req.getParameter("iid");
        int iid = Integer.parseInt(_iid);
        img.setIid(iid);
        String iname = req.getParameter("iname");
        iname = new String(iname.getBytes("iso-8859-1"), "utf-8");
        String itag = req.getParameter("itag");
        itag = new String(itag.getBytes("iso-8859-1"), "utf-8");
        img.setIname(iname);
        img.setItag(itag);
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        img.setIdate(simpleDateFormat.format(date));
        String cname = req.getParameter("cname");
        cname = new String(cname.getBytes("iso-8859-1"), "utf-8");
        Integer cid = imgService.findCid(cname);
        System.out.println(cname);
        System.out.println(cid);
        //封装类型
        img.setCid(cid);
        //-----------------------

        imgService.updateImg(img);
        ResultInfo info = new ResultInfo();
        info.setFlag(true);
        writeValue(resp, info);
    }

    public void deleteImg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer iid = Integer.parseInt(req.getParameter("iid"));
        imgService.deleteImg(iid);
        imgService.deleteFavoriteImg(iid);
        ResultInfo info = new ResultInfo();
        info.setFlag(true);
        writeValue(resp, info);
    }

    public void showComment(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String _iid = req.getParameter("iid");
        int iid = Integer.parseInt(_iid);
        List<Comment> list = imgService.loadComment(iid);
        for (Comment comment : list) {
            User user = imgService.findUserbyUid(comment.getUid());
            comment.setUser(user);
        }
        // 结果返回
        writeValue(resp, list);
    }

    public void addComment(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String text = req.getParameter("text");
        String _iid = req.getParameter("iid");
        int iid = Integer.parseInt(_iid);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(date);
        User user = (User) req.getSession().getAttribute("user");
        // 判断用户是否登录
        if (user == null) { // 未登录
            return;
        } else { // 已登录
            imgService.addComment(iid, text, user.getUid(), time);
        }
        // 结果返回
        writeValue(resp, true);
    }

    public void deleteComment(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String _comid = req.getParameter("comid");
        int comid = Integer.parseInt(_comid);
        User user = (User) req.getSession().getAttribute("user");
        if (user == null) {
            return;
        } else {
            imgService.deleteComment(comid);
        }
        // 结果返回
        writeValue(resp, true);
    }

    public void countComment(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String _iid = req.getParameter("iid");
        int iid = Integer.parseInt(_iid);
        int count = imgService.countComment(iid);

        // 结果返回
        writeValue(resp, count);
    }

    public void addSupporting(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String _comid = req.getParameter("comid");
        int comid = Integer.parseInt(_comid);
        int count = imgService.addSupport(comid);
        req.getSession().setAttribute("addFlag" + comid, true);
        // 结果返回
        writeValue(resp, count);
    }

    public void isAddSupp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String _comid = req.getParameter("comid");
        int comid = Integer.parseInt(_comid);
        ResultInfo info = new ResultInfo();
        Object flag = req.getSession().getAttribute("addFlag" + comid);
        if (flag == null) {
            info.setFlag(false);
        } else {
            info.setFlag(true);
        }
        // 结果返回
        writeValue(resp, info);
    }

    public void addNonSupporting(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String _comid = req.getParameter("comid");
        int comid = Integer.parseInt(_comid);
        int count = imgService.addNonSupport(comid);
        req.getSession().setAttribute("addFlag" + comid, true);
        // 结果返回
        writeValue(resp, count);
    }

    public void isAddNon(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String _comid = req.getParameter("comid");
        int comid = Integer.parseInt(_comid);
        ResultInfo info = new ResultInfo();
        Object flag = req.getSession().getAttribute("addFlag" + comid);
        if (flag == null) {
            info.setFlag(false);
        } else {
            info.setFlag(true);
        }
        // 结果返回
        writeValue(resp, info);
    }
}
